package com.mdd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mdd.common.R;
import com.mdd.pojo.Employee;
import com.mdd.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpServletRequest httpServletRequest){
        //构建查询条件，根据用户名查找用户
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        //查找
        Employee emp = employeeService.getOne(queryWrapper);
        //验证是否存在该用户
        if (emp==null)return R.error("登录失败，没有此用户");
        //对提交的密码进行md5加密，然后验证密码是否正确
        if (!emp.getPassword().equals(DigestUtils.md5DigestAsHex(employee.getPassword().getBytes())))
            return R.error("密码错误！");
        //查看该用户是否被禁用
        if (emp.getStatus()!=1)return R.error("该账号已被禁用");
        //登录成功
        HttpSession session = httpServletRequest.getSession();
        session.setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest httpServletRequest){
        httpServletRequest.getSession().removeAttribute("employee");
        return R.success("退出成功!");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    @CacheEvict(value = "employeeCache",allEntries = true)
    public R<String> addEmp(@RequestBody Employee employee,HttpServletRequest httpServletRequest){
        log.info(employee.toString());
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
        //通过MyBatisPlus的公共字段自动填充去实现。
        /*employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        Long nowId = (Long) httpServletRequest.getSession().getAttribute("employee");
        employee.setCreateUser(nowId);
        employee.setUpdateUser(nowId);*/
        if (employeeService.save(employee)) {
            return R.success("添加成功");
        }else {
            return R.error("添加失败");
        }
    }


    /**
     * 分页显示
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    @Cacheable( value = "employeeCache",key ="#page+'_'+#pageSize")
    public R<Page<Employee>> list(@RequestParam("page") int page ,@RequestParam("pageSize") Integer pageSize,String name){
        Page<Employee> employeePage = new Page<>(page, pageSize);
        //name有值,表示是按名字进行分页查询。
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name).orderByDesc(Employee::getUpdateTime);
        //如果name参数为null，说明为普通的分页查询。
        employeeService.page(employeePage,queryWrapper);
        return R.success(employeePage);
    }


    /**
     * 修改员工状态
     * @param employee
     * @return
     */
    @PutMapping
    @CacheEvict(value = "employeeCache",allEntries = true)
    public R<String> setStatus(@RequestBody Employee employee,HttpServletRequest request){
        //设置更新该员工的更新时间和更新此员工的用户
        /*employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));*/
        //通过id查询用户进行修改
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> getEmployeeById(@PathVariable("id") Long id){
        Employee employee = employeeService.getById(id);
        if (employee==null)return R.error("没有查询到该用户信息");
        return R.success(employee);
    }

}
